<template>
  <div class="map-wrapper">
    <div id="map-container" class="map-container"></div>
    <div v-if="!selectedOrder" class="placeholder-overlay">
      <el-empty description="请选择订单查看物流轨迹" />
    </div>
    <div v-if="loading" class="loading-overlay" v-loading="loading" element-loading-text="地图加载中...">
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { reverseGeocode } from '@/utils/geocoding'

// 声明高德地图类型
declare global {
  interface Window {
    AMap: any
  }
}

interface Props {
  selectedOrder: string
  trackActivities: Array<{
    content: string
    timestamp: string
    type: string
    color: string
    location: {
      address: string
      longitude: number
      latitude: number
    } | string  // 支持两种格式
    operator?: string
    remark?: string
    status: number
    coordinates?: [number, number]
  }>
  orderInfo?: {
    senderAddress: string
    receiverAddress: string
    senderCoords?: [number, number]
    recipientCoords?: [number, number]
  }
}

const props = defineProps<Props>()
const loading = ref(false)
const map = ref<any>(null)
const geocoder = ref<any>(null)
const markers = ref<any[]>([])

// 地址缓存
const addressCache = ref<Map<string, string>>(new Map())

// 获取坐标对应的地址
const getAddressForCoordinates = async (lng: number, lat: number): Promise<string> => {
  const coordKey = `${lng},${lat}`
  
  // 先从缓存中查找
  if (addressCache.value.has(coordKey)) {
    return addressCache.value.get(coordKey)!
  }
  
  try {
    const address = await reverseGeocode(lng, lat)
    addressCache.value.set(coordKey, address)
    return address
  } catch (error) {
    console.error('获取地址失败:', error)
    const fallbackAddress = `位置: ${lng.toFixed(6)}, ${lat.toFixed(6)}`
    addressCache.value.set(coordKey, fallbackAddress)
    return fallbackAddress
  }
}

// 物流状态映射
const statusMap = {
  1: { text: '已下单', type: 'info', color: '#909399' },
  2: { text: '待揽件', type: 'primary', color: '#409EFF' },
  3: { text: '已揽件', type: 'primary', color: '#409EFF' },
  4: { text: '运输中', type: 'warning', color: '#E6A23C' },
  5: { text: '已到达', type: 'success', color: '#67C23A' },
  6: { text: '已签收', type: 'danger', color: '#F56C6C' },
}

// 获取状态文字
const getStatusText = (status: number): string => {
  return statusMap[status as keyof typeof statusMap]?.text || '未知状态'
}

// 格式化时间戳
const formatTimestamp = (timestamp: string): string => {
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 动态加载高德地图API
const loadAMapAPI = (): Promise<void> => {
  return new Promise((resolve, reject) => {
    if (typeof window.AMap !== 'undefined') {
      resolve()
      return
    }

    const script = document.createElement('script')
    script.type = 'text/javascript'
    script.src = 'https://webapi.amap.com/maps?v=1.4.15&key=a64438d3fab59804cee20ca25fa51f2a'
    script.async = true
    
    script.onload = () => {
      console.log('高德地图API加载成功')
      resolve()
    }
    
    script.onerror = (error) => {
      console.error('高德地图API加载失败:', error)
      reject(new Error('高德地图API加载失败'))
    }
    
    document.head.appendChild(script)
  })
}

// 在initMap函数中添加
const initMap = async () => {
  try {
    loading.value = true
    await loadAMapAPI()
    
    const container = document.getElementById('map-container')
    if (!container) {
      throw new Error('地图容器不存在')
    }

    // 确保容器有明确的尺寸
    if (container.offsetWidth === 0 || container.offsetHeight === 0) {
      console.warn('地图容器尺寸为0，等待DOM渲染完成')
      await nextTick()
    }

    map.value = new window.AMap.Map('map-container', {
      zoom: 10,
      center: [116.397428, 39.90923],
      mapStyle: 'amap://styles/normal',
      zooms: [3, 20],
      dragEnable: true,
      zoomEnable: true,
      doubleClickZoom: true,
      keyboardEnable: true,
      scrollWheel: true,
      touchZoom: true,
      features: ['bg', 'point', 'road', 'building'],
      resizeEnable: true,
      rotateEnable: false
    })

    // 添加地图完成事件监听
    map.value.on('complete', () => {
      console.log('地图初始化完成')
    })

    // 添加错误事件监听
    map.value.on('error', (error: any) => {
      console.error('地图运行时错误:', error)
    })

    console.log('地图初始化成功')
    ElMessage.success('地图加载成功')
  } catch (error) {
    console.error('地图初始化失败:', error)
    ElMessage.error('地图初始化失败，请刷新页面重试')
  } finally {
    loading.value = false
  }
}

// 在地图上显示轨迹
const showTrackOnMap = async () => {
  if (!map.value) {
    console.log('地图未初始化，无法显示轨迹')
    return
  }

  // 清除之前的标记和路线
  if (markers.value.length > 0) {
    markers.value.forEach(marker => {
      map.value.remove(marker)
    })
    markers.value = []
  }
  
  // 清除地图上的所有覆盖物
  map.value.clearMap()
  
  console.log('开始在地图上显示轨迹数据，预期路线vs实际路线')
  
  // 首先绘制预期路线（起点到终点的虚线）- 底层
  await drawExpectedRoute()
  
  // 然后绘制实际轨迹路线（橙色实线）- 顶层
  await drawActualRoute()
}

// 绘制实际轨迹路线（橙色实线）
const drawActualRoute = () => {
  if (!props.trackActivities || props.trackActivities.length === 0) {
    console.log('没有轨迹活动数据')
    return
  }

  const coordinates: [number, number][] = []
  
  // 按时间戳排序
  const sortedActivities = [...props.trackActivities].sort((a, b) => 
    new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime()
  )

  sortedActivities.forEach((activity, index) => {
    let lng: number, lat: number
    
    // 优先使用coordinates字段（从index.vue处理后的数据）
    if (activity.coordinates && Array.isArray(activity.coordinates) && activity.coordinates.length === 2) {
      lng = Number(activity.coordinates[0])
      lat = Number(activity.coordinates[1])
      
      if (!isNaN(lng) && !isNaN(lat) && lng !== 0 && lat !== 0) {
        coordinates.push([lng, lat])
        console.log(`轨迹点 ${index + 1}: [${lng}, ${lat}]`)
      } else {
        console.warn(`轨迹点 ${index + 1} 坐标无效:`, activity.coordinates)
        return // 跳过无效坐标
      }
    } else {
      // 备用方案：直接从location对象获取
      if (activity.location && typeof activity.location === 'object' && 'longitude' in activity.location) {
        lng = Number(activity.location.longitude)
        lat = Number(activity.location.latitude)
        
        if (!isNaN(lng) && !isNaN(lat) && lng !== 0 && lat !== 0) {
          coordinates.push([lng, lat])
          console.log(`轨迹点 ${index + 1} (备用): [${lng}, ${lat}]`)
        } else {
          console.warn(`轨迹点 ${index + 1} 无有效坐标数据:`, activity)
          return // 跳过无效坐标
        }
      } else {
        console.warn(`轨迹点 ${index + 1} 无有效坐标数据:`, activity)
        return // 跳过无效坐标
      }
    }

    // 创建marker（只有在有效坐标时才执行）
    const coords = [lng, lat] as [number, number]
    
    // 根据位置选择不同的图标样式
    let iconImage = ''
    let iconSize = new window.AMap.Size(24, 24)
    
    // 最新的轨迹点使用精美的小车图标
    if (index === sortedActivities.length - 1) {
      iconImage = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(`
        <svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 36 36">
          <ellipse cx="18" cy="32" rx="12" ry="3" fill="rgba(0,0,0,0.2)"/>
          <rect x="6" y="18" width="24" height="10" rx="2" fill="#FF6B35" stroke="#E55A2B" stroke-width="1"/>
          <rect x="28" y="20" width="4" height="6" rx="2" fill="#FF6B35" stroke="#E55A2B" stroke-width="1"/>
          <circle cx="12" cy="28" r="3" fill="#2C3E50" stroke="#34495E" stroke-width="1"/>
          <circle cx="24" cy="28" r="3" fill="#2C3E50" stroke="#34495E" stroke-width="1"/>
          <circle cx="12" cy="28" r="1.5" fill="#95A5A6"/>
          <circle cx="24" cy="28" r="1.5" fill="#95A5A6"/>
          <rect x="8" y="20" width="6" height="4" rx="1" fill="#3498DB" stroke="#2980B9" stroke-width="0.5"/>
          <rect x="16" y="20" width="6" height="4" rx="1" fill="#3498DB" stroke="#2980B9" stroke-width="0.5"/>
          <text x="18" y="15" text-anchor="middle" font-size="8" font-weight="bold" fill="#FFFFFF">🚛</text>
        </svg>
      `)
      iconSize = new window.AMap.Size(36, 36)
    } else {
      // 其他轨迹点使用简单的圆点
      const statusInfo = statusMap[activity.status as keyof typeof statusMap] || { color: '#909399' }
      iconImage = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(`
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16">
          <circle cx="8" cy="8" r="6" fill="${statusInfo.color}" stroke="#FFFFFF" stroke-width="2"/>
          <circle cx="8" cy="8" r="3" fill="#FFFFFF"/>
        </svg>
      `)
    }
    
    const marker = new window.AMap.Marker({
      position: coords,
      icon: new window.AMap.Icon({
        image: iconImage,
        size: iconSize,
        imageOffset: new window.AMap.Pixel(-iconSize.width/2, -iconSize.height/2)
      }),
      title: `${getStatusText(activity.status)} - 坐标: ${lng.toFixed(6)}, ${lat.toFixed(6)}`,
      extData: {
        activity: activity,
        index: index,
        coordinates: coords
      },
      zIndex: index === sortedActivities.length - 1 ? 1000 : 100 + index
    })
    
    // 异步更新标记点的title为地址
    getAddressForCoordinates(lng, lat).then(address => {
      marker.setTitle(`${getStatusText(activity.status)} - ${address}`)
    })
    
    // 添加点击事件
    marker.on('click', async () => {
      // 获取转换后的地址
      const address = await getAddressForCoordinates(lng, lat)
      
      const infoWindow = new window.AMap.InfoWindow({
        content: `
          <div style="padding: 10px; min-width: 200px;">
            <h4 style="margin: 0 0 8px 0; color: #333;">${getStatusText(activity.status)}</h4>
            <p style="margin: 4px 0; color: #666;"><strong>时间:</strong> ${formatTimestamp(activity.timestamp)}</p>
            <p style="margin: 4px 0; color: #666;"><strong>地点:</strong> ${address}</p>
            <p style="margin: 4px 0; color: #666;"><strong>坐标:</strong> ${lng.toFixed(6)}, ${lat.toFixed(6)}</p>
            <p style="margin: 4px 0; color: #666;"><strong>描述:</strong> ${activity.content}</p>
            ${activity.operator ? `<p style="margin: 4px 0; color: #666;"><strong>操作员:</strong> ${activity.operator}</p>` : ''}
            ${activity.remark ? `<p style="margin: 4px 0; color: #666;"><strong>备注:</strong> ${activity.remark}</p>` : ''}
          </div>
        `,
        offset: new window.AMap.Pixel(0, -30)
      })
      infoWindow.open(map.value, marker.getPosition())
    })
    
    map.value.add(marker)
    markers.value.push(marker)
  })

  console.log(`总共处理了 ${coordinates.length} 个有效坐标点`)
  
  // 绘制实际轨迹路线（橙色实线，基于真实轨迹数据）
  if (coordinates.length > 1) {
    const actualRoute = new window.AMap.Polyline({
      path: coordinates,
      strokeColor: '#FF6B35',      // 橙色
      strokeWeight: 6,             // 较粗的线条，突出实际路径
      strokeOpacity: 1.0,          // 完全不透明
      strokeStyle: 'solid',        // 实线样式
      lineJoin: 'round',
      lineCap: 'round',
      zIndex: 60,                  // 在预期路线上方
      showDir: true                // 显示方向箭头
    })
    
    map.value.add(actualRoute)
    
    console.log(`✅ 实际轨迹路线（橙色实线）绘制完成，包含 ${coordinates.length} 个真实轨迹点`)
  } else if (coordinates.length === 1) {
    map.value.setCenter(coordinates[0])
    map.value.setZoom(15)
    console.log('📍 只有一个轨迹点，设置地图中心到该位置')
  }
  
  // 调整地图视野
  // 调整地图视野
  // 在showTrackOnMap函数的最后部分
  setTimeout(() => {
  try {
    if (coordinates.length === 0) {
      console.warn('没有有效坐标，无法调整地图视野')
      return
    }
    
    // 使用setFitView方法，这是更可靠的方式
    if (coordinates.length === 1) {
      // 单个点时设置中心和缩放
      map.value.setCenter(coordinates[0])
      map.value.setZoom(15)
    } else {
      // 多个点时让地图自动适应
      map.value.setFitView(null, false, [20, 20, 20, 20]) // 添加边距
    }
    
    console.log('地图视野已调整到轨迹范围')
  } catch (viewError) {
    console.warn('调整地图视野失败:', viewError)
    // 备用方案：手动设置到第一个坐标点
    if (coordinates.length > 0) {
      map.value.setCenter(coordinates[0])
      map.value.setZoom(12)
    }
  }
}, 500)
  
  if (coordinates.length > 0) {
    ElMessage.success(`成功在地图上显示 ${coordinates.length} 个轨迹点，当前位置已用🚛标记`)
  } else {
    ElMessage.warning('无法获取有效坐标，无法在地图上显示轨迹')
  }
}

// 绘制预期路线（起点到终点的直线）
const drawExpectedRoute = async () => {
  if (!props.orderInfo) {
    console.log('没有订单信息，跳过预期路线绘制')
    return
  }
  
  // 直接使用订单信息中的坐标，不再进行地址解析
  let startCoords: [number, number] | null = null
  let endCoords: [number, number] | null = null
  
  if (props.orderInfo.senderCoords && 
      !isNaN(props.orderInfo.senderCoords[0]) && 
      !isNaN(props.orderInfo.senderCoords[1])) {
    startCoords = props.orderInfo.senderCoords
  }
  
  if (props.orderInfo.recipientCoords && 
      !isNaN(props.orderInfo.recipientCoords[0]) && 
      !isNaN(props.orderInfo.recipientCoords[1])) {
    endCoords = props.orderInfo.recipientCoords
  }
  
  if (startCoords && endCoords) {
    // 创建起点和终点标记
    const startMarker = new window.AMap.Marker({
      position: startCoords,
      icon: new window.AMap.Icon({
        image: 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(`
          <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
            <circle cx="16" cy="16" r="14" fill="#52C41A" stroke="#FFFFFF" stroke-width="2"/>
            <text x="16" y="20" text-anchor="middle" font-size="12" font-weight="bold" fill="#FFFFFF">起</text>
          </svg>
        `),
        imageOffset: new window.AMap.Pixel(-16, -16)
      }),
      zIndex: 500
    })
    
    const endMarker = new window.AMap.Marker({
      position: endCoords,
      icon: new window.AMap.Icon({
        image: 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(`
          <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
            <circle cx="16" cy="16" r="14" fill="#F5222D" stroke="#FFFFFF" stroke-width="2"/>
            <text x="16" y="20" text-anchor="middle" font-size="12" font-weight="bold" fill="#FFFFFF">终</text>
          </svg>
        `),
        imageOffset: new window.AMap.Pixel(-16, -16)
      }),
      zIndex: 500
    })
    
    map.value.add(startMarker)
    map.value.add(endMarker)
    markers.value.push(startMarker, endMarker)
    
    // 绘制预期路线（蓝色虚线）
    // 绘制预期路线（蓝色虚线，起点到终点直线）
    const expectedRoute = new window.AMap.Polyline({
      path: [startCoords, endCoords],
      strokeColor: '#1890FF',      // 蓝色
      strokeWeight: 4,             // 较细的线条
      strokeStyle: 'dashed',       // 虚线样式
      strokeDasharray: [15, 10],   // 虚线间隔
      strokeOpacity: 0.7,          // 半透明
      lineJoin: 'round',
      lineCap: 'round',
      zIndex: 40                   // 在实际路线下方
    })
    
    map.value.add(expectedRoute)
    
    console.log('✅ 预期路线（蓝色虚线）绘制完成：起点到终点直线距离')
  } else {
    console.log('无法获取起点或终点坐标，跳过预期路线绘制')
  }
}

// 监听轨迹数据变化
watch(() => props.trackActivities, () => {
  if (props.selectedOrder && props.trackActivities.length > 0) {
    showTrackOnMap()
  }
}, { deep: true })

// 监听选中订单变化
watch(() => props.selectedOrder, (newOrder) => {
  if (newOrder && map.value) {
    showTrackOnMap()
  } else if (map.value) {
    map.value.clearMap()
  }
})

// 添加窗口大小变化处理
const handleResize = () => {
  if (map.value && map.value.getContainer()) {
    nextTick(() => {
      try {
        // 重新计算地图容器大小
        const container = document.getElementById('map-container')
        if (container && container.offsetWidth > 0 && container.offsetHeight > 0) {
          // 使用高德地图的正确方法重新计算尺寸
          map.value.getSize()
          
          // 如果有标记点，重新适应视图
          if (markers.value.length > 0) {
            setTimeout(() => {
              try {
                map.value.setFitView(markers.value, false, [20, 20, 20, 20])
              } catch (e) {
                console.warn('设置地图视图时出错:', e)
              }
            }, 100)
          }
        }
      } catch (error) {
        console.warn('地图重绘时出现错误:', error)
      }
    })
  }
}

// 防抖处理
let resizeTimer: ReturnType<typeof setTimeout> | null = null
const debouncedResize = () => {
  if (resizeTimer) {
    clearTimeout(resizeTimer)
  }
  resizeTimer = setTimeout(handleResize, 300)
}

// 监听轨迹数据变化
watch(() => props.trackActivities, () => {
  if (props.selectedOrder && props.trackActivities.length > 0) {
    showTrackOnMap()
  }
}, { deep: true })

// 监听选中订单变化
watch(() => props.selectedOrder, (newOrder) => {
  if (newOrder && map.value) {
    showTrackOnMap()
  } else if (map.value) {
    map.value.clearMap()
  }
})

onMounted(() => {
  initMap()
  // 添加窗口大小变化监听
  window.addEventListener('resize', debouncedResize)
})

onUnmounted(() => {
  // 清理事件监听
  window.removeEventListener('resize', debouncedResize)
  if (resizeTimer) {
    clearTimeout(resizeTimer)
  }
  if (map.value) {
    try {
      map.value.destroy()
    } catch (error) {
      console.warn('销毁地图时出错:', error)
    }
  }
})
</script>

<style scoped>
.map-wrapper {
  position: relative;
  overflow: visible;
  min-height: 500px;
}

.map-container {
  width: 100%;
  height: 500px;
  position: relative;
  z-index: 1;
  transition: all 0.3s ease;
}

.placeholder-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.9);
  z-index: 10;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.8);
  z-index: 20;
}

/* 防止地图在缩放时出现布局问题 */
:deep(.amap-container) {
  position: relative !important;
}

/* 地图控件样式 */
:deep(.amap-toolbar),
:deep(.amap-scale) {
  z-index: 1000 !important;
  pointer-events: auto !important;
}

:deep(.amap-toolbar .amap-btn) {
  background: #fff !important;
  border: 1px solid #ccc !important;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1) !important;
}

:deep(.amap-toolbar .amap-btn:hover) {
  background: #f5f5f5 !important;
}
</style>